package cn.glc.daily.life.common.utils;

import cn.glc.daily.life.common.enums.GlobalCodeEnum;
import cn.glc.daily.life.common.exceptions.Business;
import lombok.Data;

import static cn.glc.daily.life.common.enums.GlobalCodeEnum.HttpStatusEnum.FAIL;
import static cn.glc.daily.life.common.enums.GlobalCodeEnum.HttpStatusEnum.SUCCESS;

/**
 * 全局对外统一返回对象
 *
 * @author simon
 * @date 2020/6/2 10:56
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Data
public class JsonResult<T> {

    /**
     * 返回的状态码
     */
    private String code;
    /**
     * 状态码描述
     */
    private String msg;
    /**
     * 返回的自定义封装的结果集
     */
    private Object data;
    /**
     * 时间
     */
    private long ts = System.currentTimeMillis();


    public JsonResult(GlobalCodeEnum.HttpStatusEnum code) {
        this.code = code.getCode();
        this.msg = code.getMsg();
        this.data = null;
    }

    public JsonResult(GlobalCodeEnum.HttpStatusEnum code, Object data) {
        this.code = code.getCode();
        this.msg = code.getMsg();
        this.data = data;
    }

    private JsonResult(String code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }

    /**
     * 正常返回
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T> JsonResult<T> of(T t) {
        return returnSuccess(t);
    }

    /**
     * 自定义异常返回
     *
     * @param business
     * @return
     */
    public static JsonResult of(Business business) {
        return returnFailure(business);
    }

    /**
     * 非自定义异常返回/自定义异常返回
     * 判断异常类型是否为Business,如果是则为自定义异常/反之则是系统异常
     *
     * @param e
     * @return
     */
    public static JsonResult of(Exception e) {
        return e instanceof Business ? of((Business) e) : returnCustomFailure(e.getMessage());
    }

    /**
     * 返回成功
     *
     * @param data
     * @return
     */
    public static JsonResult returnSuccess(Object data) {
        return new JsonResult(SUCCESS, data);
    }

    /**
     * 返回成功
     *
     * @return
     */
    public static JsonResult returnSuccess() {
        return new JsonResult(SUCCESS);
    }

    /**
     * 返回失败
     *
     * @return
     */
    public static JsonResult returnFailure() {
        return new JsonResult(FAIL);
    }

    /**
     * 返回失败
     *
     * @param code
     * @param msg
     * @return
     */
    public static JsonResult returnFailure(String code, String msg) {
        return new JsonResult(code, msg);
    }

    /**
     * 自定义追加异常消息
     *
     * @param msg
     * @return
     */
    public static JsonResult returnCustomFailure(String msg) {
        return new JsonResult(FAIL, msg);
    }

    /**
     * 抛出定制化异常
     *
     * @param e
     * @return
     */
    public static JsonResult returnFailure(Business e) {
        return new JsonResult(e.code(), e.msg());
    }
}
